var app = getApp();
var vp = require('../../resource/js/vp.js');
Page({
  data: {
    hasFamilyHistory: false,
    commonDiseases: [
      { name: '高血压' }, { name: '糖尿病' }, { name: '冠心病' },
      { name: '脑卒中' }, { name: '恶性肿瘤' }, { name: '精神疾病' },
      { name: '心脏病' }, { name: '阿尔茨海默病' }, { name: '哮喘' },
      { name: '痛风' }, { name: '骨质疏松' }, { name: '血脂异常' }
    ],
    selectedDiseases: [],
    relations: [
      '爸爸', '妈妈', '老公', '老婆', '儿子', 
      '女儿', '爷爷', '奶奶', '外公', '外婆','其他'
    ],
    customDiseases: []
  },

  onLoad(options) {
    // 初始化数据，可从后台获取
	const healthData = wx.getStorageSync('activeUserHealthNote')
	if(healthData.family.hasFamilyHistory){
		this.setData({
		  hasFamilyHistory: healthData.family.hasFamilyHistory || false,
		  selectedDiseases: healthData.family.selectedDiseases || [],
		  customDiseases: healthData.family.customDiseases || []
		});
	}
	this.getCommonDisease()
    const eventChannel = this.getOpenerEventChannel();
    eventChannel.on('addFamilyNote', (data) => {
		console.log("from data",data)
      this.setData({
        hasFamilyHistory: data.hasFamilyHistory || false,
        selectedDiseases: data.selectedDiseases || [],
        customDiseases: data.customDiseases || []
      });
    });
  },
  getCommonDisease:function(){
	  var that = this
	    app.util.request({
	  	  url: 'Familydoctor/getCommonDisease',
	  	  data: {
	  	  },
	  	  success(res) {
	  		  var data = res.data.data;
			  console.log('familyData',data)
	  		  that.setData({
	  			  'commonDiseases':data || this.data.commonDiseases
	  		  })
	  	  }
	    })
  },
  // 切换有无家族史
  toggleFamilyHistory(e) {
    const value = e.currentTarget.dataset.value === 'true';
    this.setData({
      hasFamilyHistory: value
    });
  },


  // 添加自定义疾病
  addDisease(e) {
	  const { name } = e.currentTarget.dataset;
    const newDiseases = [...this.data.customDiseases, {
      id: Date.now(),
      name: name,
      relation: '',
      relationIndex: 0,
      age: ''
    }];
    
    this.setData({
      customDiseases: newDiseases
    });
  },

  // 输入疾病名称
  inputDiseaseName(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`customDiseases[${index}].name`]: e.detail.value
    });
  },

  // 改变亲属关系
  changeRelation(e) {
    const { index } = e.currentTarget.dataset;
    const relationIndex = e.detail.value;
    const relation = this.data.relations[relationIndex];
    
    this.setData({
      [`customDiseases[${index}].relationIndex`]: relationIndex,
      [`customDiseases[${index}].relation`]: relation
    });
  },

  // 输入确诊年龄
  inputDiseaseAge(e) {
    const { index } = e.currentTarget.dataset;
    this.setData({
      [`customDiseases[${index}].age`]: e.detail.value
    });
  },

  // 删除疾病记录
  removeDisease(e) {
    const { index } = e.currentTarget.dataset;
    wx.showModal({
      title: '确认删除',
      content: '确定要删除此记录吗？',
      success: (res) => {
        if (res.confirm) {
          const newDiseases = [...this.data.customDiseases];
          newDiseases.splice(index, 1);
          this.setData({
            customDiseases: newDiseases
          });
        }
      }
    });
  },

  // 保存数据
  save() {
    // 验证必填项
    if (this.data.hasFamilyHistory) {
      for (let i = 0; i < this.data.customDiseases.length; i++) {
        const disease = this.data.customDiseases[i];
        if (!disease.name || !disease.relation || !disease.age) {
          wx.showToast({
            title: `请完善第${i + 1}条记录的信息`,
            icon: 'none'
          });
          return;
        }
      }
    }
    
    // 准备数据
    const familyData = {
      hasFamilyHistory: this.data.hasFamilyHistory,
      selectedDiseases: this.data.selectedDiseases,
      customDiseases: this.data.customDiseases
    };
	console.log(familyData);
      const that = this;
        // 模拟保存操作
        wx.showLoading({
          title: '保存中...',
        });
		let activeUser = wx.getStorageSync('activeUser')
		familyData.type = 1;
		familyData.family_id = activeUser.id
        let jsonData = JSON.stringify(familyData);
        app.util.request({
        	url: 'Familydoctor/createFamilyNoteData',
        	data: jsonData,
        	method:'POST',
        	headers: {
        		'Content-Type': 'application/json',
        	},
        	success(res) {
        		console.log(res)
        		if(res.data.code){	
    				wx.hideLoading();
    				wx.showToast({
    				  title: '保存成功',
    				  icon: 'success'
    				});
    				that.setData({
    				  isEditing: false
    				});
					const eventChannel = that.getOpenerEventChannel();
					eventChannel.emit('addFamilyNote', res.data.data.content);
    				setTimeout(() => {
    				  wx.navigateBack();
    				}, 1500);
        		}else{
        			wx.showToast({ title: '提交失败请重试' });
        		}
        	}
        })
  }
});